import {
  downloadCommonOne
} from '@/api/common'


export function timeFix() {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好'
}

export function welcome() {
  const arr = ['休息一会儿吧', '准备吃什么呢?', '要不要打一把 DOTA', '我猜你可能累了']
  const index = Math.floor(Math.random() * arr.length)
  return arr[index]
}

/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent() {
  const event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}

export function handleScrollHeader(callback) {
  let timer = 0
  let beforeScrollTop = window.pageYOffset
  callback = callback || function () {}
  window.addEventListener(
    'scroll',
    event => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        let direction = 'up'
        const afterScrollTop = window.pageYOffset
        const delta = afterScrollTop - beforeScrollTop
        if (delta === 0) {
          return false
        }
        direction = delta > 0 ? 'down' : 'up'
        callback(direction)
        beforeScrollTop = afterScrollTop
      }, 50)
    },
    false
  )
}

export function isIE() {
  const bw = window.navigator.userAgent
  const compare = (s) => bw.indexOf(s) >= 0
  const ie11 = (() => 'ActiveXObject' in window)()
  return compare('MSIE') || ie11
}

/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate(id = '', timeout = 1500) {
  if (id === '') {
    return
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id))
  }, timeout)
}
export function scorePassword(pass) {
  let score = 0
  if (!pass) {
    return score
  }
  // award every unique letter until 5 repetitions
  const letters = {}
  for (let i = 0; i < pass.length; i++) {
    letters[pass[i]] = (letters[pass[i]] || 0) + 1
    score += 5.0 / letters[pass[i]]
  }

  // bonus points for mixing it up
  const variations = {
    digits: /\d/.test(pass),
    lower: /[a-z]/.test(pass),
    upper: /[A-Z]/.test(pass),
    nonWords: /\W/.test(pass)
  }

  let variationCount = 0
  for (var check in variations) {
    variationCount += (variations[check] === true) ? 1 : 0
  }
  score += (variationCount - 1) * 10

  return parseInt(score)
}

export function routerEach(router, url) {
  const arr = []
  router.forEach(item => {
    const tem = {
      ...item
    }
    if (tem.path == url) {
      tem.hidden = false
    }
    if (tem.children && tem.children.length) {
      tem.children = routerEach(tem.children, url)
    }
    arr.push(tem)
  })
  return arr
}

import JsEncrypt from 'jsencrypt'
import {
  get
} from 'store'
var publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8HaSSz1ARBkTOmythz8Zk2oKWYaLU1gA1MsQaKRj5UwA/DMdKVy7CDE070PCecTiBfqCDmdvzOn+G0G/gr4p6KXeXI00KZArXPBDSd0HSUGwuCsFpLppr1q1H4MluvMOsaiAdh7mLCnMxOag0Vjq6oBbXXM2lYkpTxBD4w90eiQIDAQAB";
export function encrypt(data) { //Rsa加密
  var en = new JsEncrypt();
  en.setPublicKey(publicKey);
  return en.encrypt(data)
}

export function fileExport(res, title) { //导出
  let BLOB = new Blob([res]);
  console.log(BLOB)
  if (BLOB) {
    // for IE
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(BLOB, title);
    }
    // for Non-IE (chrome, firefox etc.)
    else {
      var a = document.createElement('a');
      document.body.appendChild(a);
      a.style = 'display: none';
      var url = window.URL.createObjectURL(BLOB);
      a.href = url;
      a.download = title;
      a.click();
      a.remove();
      window.URL.revokeObjectURL(url);
    }

  }
}

export function fileDownload(fileName, filePath) { //下载

  if (process.env.NODE_ENV !== 'development') {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', filePath, true);
    xhr.responseType = 'blob';
    xhr.onload = function () {
      if (xhr.status === 200) {
        fileExport(xhr.response, fileName)
      }
    };
    xhr.send();
  } else {
    var a = document.createElement('a');
    a.target = '_blank'
    var event = new MouseEvent('click');
    a.href = filePath;
    a.download = fileName;
    console.log(a)
    a.dispatchEvent(event);
  }
  // downloadCommonOne({
  //   previewPath:filePath
  // }).then(res=>{
  //   fileExport(res,fileName)
  // })
  // console.log(fileName,111)
}

export function fileDownloadByRequest(fileName, filePath) { //下载

  downloadCommonOne({
    previewPath: filePath
  }).then(res => {
    fileExport(res, fileName)
  })

}


//比较两个日期的大小
export function comparedate(date1 = new Date(), date2 = new Date()) {

  let oDate1 = new Date(date1);
  let oDate2 = new Date(date2);
  if (oDate1.getTime() >= oDate2.getTime()) {
    return true;
  } else {
    return false;
  }
}


//计算两个日期之间的天数
export function dateBetweenDays(date1 = new Date(), date2 = new Date()) {
  let oDate1 = new Date(date1);
  let oDate2 = new Date(date2);
  var times = oDate1.getTime() - oDate2.getTime()
  if (times < 0) {
    return 0;
  }
  return parseInt(times / 1000 / 60 / 60 / 24) + 1;
}
//日期
export function dateFormatter(str) { //默认返回yyyy-MM-dd HH-mm-ss
  if (!str) {
    return '';
  }
  var hasTime = arguments[1] != false ? true : false; //可传第二个参数true，返回yyyy-MM-dd
  var d = new Date(str);
  var year = d.getFullYear();
  var month = (d.getMonth() + 1) < 10 ? '0' + (d.getMonth() + 1) : (d.getMonth() + 1);
  var day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate();
  var hour = d.getHours() < 10 ? '0' + d.getHours() : d.getHours();
  var minute = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes();
  var second = d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds();
  if (!hasTime) {
    return [year, month, day].join('-') + " " + [hour, minute, second].join(':');
  } else {
    return [year, month, day].join('-');
  }
}

//表格合并
export function mergeCell(data, keys) {
  //data为表格数据,keys为合并依据
  let tempValue = ''
  for (let kIndex = 0; kIndex < keys.length; kIndex++) {
    const key = keys[kIndex]
    const spanKey = key + 'Span'
    for (let i = 0; i < data.records.length;) {
      var rowSpan = 0
      if (tempValue[key] !== data.records[i][key]) {
        tempValue = data.records[i][key]
        for (let j = i; j < data.records.length; j++) {
          const item = data.records[j]
          if (item[key] === tempValue) {
            rowSpan += 1
          } else {
            break
          }
        }
      }
      data.records[i][spanKey] = rowSpan
      for (let j = i + 1; j < i + rowSpan && j < data.records.length; j++) {
        data.records[j][spanKey] = 0
      }
      i += rowSpan
    }
  }
  return data
}

//获取月初月末
export function getFirstLaterDay() {
  var date = new Date()
  date.setDate(1)
  var month = parseInt(date.getMonth() + 1)
  var day = date.getDate()
  if (month < 10) {
    month = '0' + month
  }
  if (day < 10) {
    day = '0' + day
  }
  const getCurrentMonthFirstDay = date.getFullYear() + '-' + month + '-' + day
  //月末
  var endDate = new Date()
  var currentMonth = endDate.getMonth()
  var nextMonth = ++currentMonth
  var nextMonthFirstDay = new Date(endDate.getFullYear(), nextMonth, 1)
  var oneDay = 1000 * 60 * 60 * 24
  var lastTime = new Date(nextMonthFirstDay - oneDay)
  var endMonth = parseInt(lastTime.getMonth() + 1)
  var endDay = lastTime.getDate()
  if (endMonth < 10) {
    endMonth = '0' + endMonth
  }
  if (endDay < 10) {
    endDay = '0' + endDay
  }
  const getCurrentMonthLaterDay = endDate.getFullYear() + '-' + endMonth + '-' + endDay
  return [getCurrentMonthFirstDay, getCurrentMonthLaterDay]

}

/**
 * 获取本周一到周几的日期
 * dateString 当天日期
 * days 要展示的数组长度
 */
export function getMondayToXday(dateString, days) {
  let dateStringReg = /^\d{4}[/-]\d{1,2}[/-]\d{1,2}$/;

  if (dateString.match(dateStringReg)) {
    let presentDate = new Date(dateString),
      today = presentDate.getDay() !== 0 ? presentDate.getDay() : days;

    return Array.from(new Array(days), function (val, index) {
      return formatDate(new Date(presentDate.getTime() - (today - index - 1) * 24 * 60 * 60 * 1000));
    });

  } else {
    throw new Error('dateString should be like "yyyy-mm-dd" or "yyyy/mm/dd"');
  }

  function formatDate(date) {
    return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
  }
}

//获取宽度更改字体
export function fontSize(res) {
  let clientWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
  if (!clientWidth) return
  let fontSize = 100 * (clientWidth / 1920)
  return res * fontSize
}